package cn.minhx.domain.strategy.service.rule.tree.impl;

import cn.minhx.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.minhx.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.minhx.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 次数锁节点
 *
 * @author min
 */
@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    // 用户抽奖次数，后续完成这部分流程开发的时候，从数据库/Redis中读取
    private Long userRaffleCount = 0L;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Long awardId, String ruleValue) {
        log.info("决策树引擎【次数锁节点】开始 userId={} strategyId={} awardId={} ruleValue={}", userId, strategyId, awardId, ruleValue);

        long needRaffleTime;
        try {
            needRaffleTime = Long.parseLong(ruleValue);
        } catch (Exception e) {
            log.error("决策树引擎【次数锁节点】异常 ruleValue【{}】配置不正确 userId={} strategyId={} awardId={} ruleValue={}", ruleValue, userId, strategyId, awardId, ruleValue, e);
            throw new RuntimeException("决策树引擎【次数锁节点】异常 ruleValue【" + ruleValue + "】配置不正确！");
        }

        // 用户已抽奖次数
        long userRaffleCount = this.userRaffleCount;

        // 用户已抽奖次数小于配置的规则锁次数，拦截
        if (userRaffleCount < needRaffleTime) {
            log.info("决策树引擎【次数锁节点】用户抽奖次数【{}】小于阈值【{}】 userId={} strategyId={} awardId={} ruleValue={}", userRaffleCount, needRaffleTime, userId, strategyId, awardId, ruleValue);
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .build();
        }

        // 用户已抽奖次数大于配置的规则锁次数
        log.info("决策树引擎【次数锁节点】用户抽奖次数【{}】大于阈值【{}】 userId={} strategyId={} awardId={} ruleValue={}", userRaffleCount, needRaffleTime, userId, strategyId, awardId, ruleValue);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }

}
